package com.yeskery.nut.http.controller;

import com.yeskery.nut.core.*;

/**
 * 默认的 Nut <code>Controller</code>，该 <code>Controller</code> 会返回
 * {@link DefaultContentHelper#getDefaultHtml(String)} 中的默认 HTML 响应
 *
 * @author sprout
 * 2019-03-16 10:51
 * @version 1.0
 *
 * @see com.yeskery.nut.core.Controller
 * @see DefaultContentHelper
 */
public class DefaultController implements Controller {

	/** 响应码 */
	private Integer code;

	/** 响应内容 */
	private final String content;

	/**
	 * 构建一个 {@link DefaultController} 对象，默认的响应码为 {@link ResponseCode#OK}
	 * @param content 响应的内容
	 */
	public DefaultController(String content) {
		this.content = content;
	}

	/**
	 * 构建一个 {@link DefaultController} 对象
	 * @param code 响应码
	 * @param content 响应的内容
	 */
	public DefaultController(Integer code, String content) {
		this.code = code;
		this.content = content;
	}

	/**
	 * 构建一个 {@link DefaultController} 对象，默认的响应码为 {@link ResponseCode#OK}
	 */
	public DefaultController() {
		ResponseNutException responseNutException = (ResponseNutException) RequestApplicationContext
				.getResource(ErrorController.REQUEST_EXCEPTION_HOLDER_KEY);
		if (responseNutException == null) {
			throw new NutException("ResponseNutException Can Not Be Empty.");
		}
		this.code = responseNutException.getCode();
		this.content = responseNutException.getMessage();
	}

	@Override
	public void doGet(Request request, Response response, Execution execution) {
		if (code != null && code != ResponseCode.OK.getCode()) {
			response.setCode(code);
		}
		response.writeHtml(DefaultContentHelper.getDefaultHtml(content));
	}

	@Override
	public void doPost(Request request, Response response, Execution execution) {
		doGet(request, response, execution);
	}

	@Override
	public void doPut(Request request, Response response, Execution execution) {
		doGet(request, response, execution);
	}

	@Override
	public void doDelete(Request request, Response response, Execution execution) {
		doGet(request, response, execution);
	}
}
